package com.eastcom.common.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

/**
 * @since 2010
 * @author Dongping Mao
 */

public abstract class AbstractSession {

	protected static DataSource dataSource=null;
	
	protected static int reGetCount=3;
	
	protected boolean closed=false;
	
	protected void initialDataSource() throws Exception{
		if(dataSource==null){
			
		    synchronized(DataSource.class){
		        try{
			        if(dataSource==null){
				        dataSource=this.createDataSource();
			        }
		        }
			    catch(Exception e){
				    e.printStackTrace();
				    throw e;
			    }
			    finally{
			    	DataSource.class.notifyAll();
			    }
		    }
		    
		}
	}
	
	protected void configConnection(Connection con, boolean autoCommit, int isolationLevel) throws SQLException {
		// TODO Auto-generated method stub
		con.setAutoCommit(autoCommit);
		con.setTransactionIsolation(isolationLevel);
	}
	
	protected Connection getNewConnection() throws SQLException{
		if(dataSource==null)
			return null;
		
		int index=0;
		
		while(index<reGetCount){
		    Connection con=dataSource.getConnection();
		    if(!con.isClosed())
		    	return con;
		    
		    try{
		        con.close();
		    }
		    catch(Exception e){}
		    
		    index++;
		}
		
		return null;
	}
	
	
	public boolean isClosed() {
		return closed;
	}

    public abstract Connection connection();
	
    public abstract Transaction beginTransaction()throws SQLException;

    public abstract Transaction getTransaction();
    
	public abstract Connection getConnection() throws SQLException ;
	
	public abstract void close();
	
	protected abstract void removeCurrentTransaction();
	
	protected abstract DataSource createDataSource()throws Exception;
	
	protected abstract Boolean initialTransactionConnection(Connection con)throws Exception;
	
	protected abstract void initialConnection()throws SQLException;
	
	protected abstract void recoverConnection(Connection con)throws Exception;
	
}
